<script setup lang="ts">
import { noticeList } from "@/api/home/index"
import { resetPwdApi } from "@/api/login/index"
import type { FormInstance, FormRules } from 'element-plus'
import { ElDropdown, ElDropdownMenu, ElDropdownItem, ElMessageBox, ElMessage } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { useStorage } from '@/hooks/web/useStorage'
import { resetRouter } from '@/router'
import { useRouter } from 'vue-router'
import { loginOutApi } from '@/api/login'
import { useDesign } from '@/hooks/web/useDesign'
import { useTagsViewStore } from '@/store/modules/tagsView'
import LockDialog from './components/LockDialog.vue'
import { ref, computed, onMounted } from 'vue'
import LockPage from './components/LockPage.vue'
import { useLockStore } from '@/store/modules/lock'
import { useAppStoreWithOut } from '@/store/modules/app'
import { reactive } from 'vue'
const { getStorage } = useStorage()
const appStore = useAppStoreWithOut()
const lockStore = useLockStore()

const getIsLock = computed(() => lockStore.getLockInfo?.isLock ?? false)

const tagsViewStore = useTagsViewStore()

const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('user-info')

const { t } = useI18n()

const { clear } = useStorage()

const { replace } = useRouter()

const loginOut = () => {
  ElMessageBox.confirm(t('common.loginOutMessage'), t('common.reminder'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      // const res = await loginOutApi().catch(() => { })
      // if (res) {

      // }
      clear()
      tagsViewStore.delAllViews()
      resetRouter() // 重置静态路由表
      replace('/login')
    })
    .catch(() => { })
}
const userInfo = getStorage(appStore.getUserInfo)
console.log(userInfo);

const dialogVisible = ref<boolean>(false)

// 锁定屏幕
const lockScreen = () => {
  dialogVisible.value = true
}

const toDocument = () => {
  window.open('https://element-plus-admin-doc.cn/')
}
const state = reactive({
  my_Info: {
    user: {
      dept: {

      },
      roles: [{
        roleName: "暂无信息"
      }]
    }
  } as any,
  ruleForm: {} as any,
  tableData: [] as any,
  bot: false,
  form: {
    pageNum: 1,
    pageSize: 10000,
    orderByColumn: "createTime",
    isAsc: "desc"
  }

})

onMounted(() => {
  state.my_Info = JSON.parse(sessionStorage.getItem("my_Info"))
  console.log("个人信息：", state.my_Info);

})
const ruleFormRef = ref<FormInstance>()
const dialogVisibleEdit = ref(false)
const handleClose = () => {
  dialogVisibleEdit.value = false
  state.ruleForm = {}
}
const openEdit = () => {
  dialogVisibleEdit.value = true

}
interface RuleForm {
  old_password: string
  password: string
  again_password: string
}
const rules = reactive<FormRules<RuleForm>>({
  old_password: [
    { required: true, message: '请输入旧密码', trigger: 'blur', },
    { pattern: /^[A-Za-z0-9]+$/, message: '密码只能包含英文字母和数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur', },
    { pattern: /^[A-Za-z0-9]+$/, message: '密码只能包含英文字母和数字', trigger: 'blur' }
  ],
  again_password: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]+$/, message: '密码只能包含英文字母和数字', trigger: 'blur' }
  ],
})
const loading = ref(false)
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      console.log('submit!')
      if (state.ruleForm.again_password != state.ruleForm.password) {
        ElMessage.error(`两次输入密码不一致！`)
        loading.value = false
        return
      }
      let params = {
        oldPassword: state.ruleForm.old_password,
        newPassword: state.ruleForm.again_password
      }
      resetPwdApi(params).then((res: any) => {
        ElMessage.success(res.msg)
        loading.value = false
        handleClose()
      }).catch((res: any) => {
        console.log(res);
        loading.value = false
        ElMessage.error(res.msg)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const noticeListApi = async (params) => {
  await noticeList(params).then((res: any) => {
    state.tableData = [...state.tableData, ...res.rows]
    let arr: any = localStorage.getItem("xxtableData") ? JSON.parse(localStorage.getItem("xxtableData")): []
    console.log("通知消息：",arr, res);
    if(state.tableData.length==0){
      state.bot = false
      return
    }
    if (arr.length == state.tableData.length) {
      state.bot = false
    } else {
      state.bot = true
    }
    

  })
}
const botClick=()=>{
  // console.log("dianji");
  state.bot = false
  localStorage.setItem("xxtableData", JSON.stringify(state.tableData))
}
noticeListApi(state.form)
</script>

<template>
  <ElDropdown class="custom-hover" :class="prefixCls" trigger="click">
    <div class="flex items-center">
      <el-badge class="item" :is-dot="state.bot">
        <el-icon style="vertical-align: middle" @click="botClick()">
          <Bell />
        </el-icon>
      </el-badge>
    </div>
    <template #dropdown>
      <ElDropdownMenu style="padding: 0;">
        <div class="login_userinfo">
          <p class="fontw700 fonts16" style="margin-bottom: 16px;">通知</p>
          <ul class="login_userinfo_ul" id="scroll_ul" v-if="state.tableData.length != 0" style="overflow-y: auto"
            infinite-scroll-distance="100">
            <li class="flex" style="align-items: center;" v-for="(item, index) in state.tableData" :key="index">
              <img src="@/assets/imgs/bell1.png" alt="" />
              <div class="">
                <p class="fontz fonts14 login_userinfo_p1">{{ item.noticeTitle }}</p>
                <p class="fontz12 gray ">{{ item.noticeContent }}</p>
                <p class="fontz12 gray ">{{ item.createTime }}</p>
              </div>
            </li>
          </ul>
          <el-empty description="暂无数据" v-if="state.tableData.length == 0" />
        </div>
      </ElDropdownMenu>
    </template>
  </ElDropdown>
  <ElDropdown class="custom-hover" :class="prefixCls" trigger="click">
    <div class="flex items-center">
      <img src="@/assets/imgs/logo.png" alt="" class="w-[calc(var(--logo-height)-25px)] rounded-[50%]" />
      <span class="<lg:hidden text-14px pl-[5px] text-[var(--top-header-text-color)]">{{
    state.my_Info.user.nickName || '暂无信息' }}</span>
      <el-icon size="16" style="vertical-align: middle;margin-left: 16px;">
        <SwitchButton />
      </el-icon>
    </div>
    <template #dropdown>
      <ElDropdownMenu style="padding: 0;">
        <div class="login_userinfo">
          <p class="fontw700 fonts16" style="margin-bottom: 16px;">账号信息</p>
          <p class="fontz fonts14 login_userinfo_p"><span>所在部门</span>：{{ state.my_Info.user.dept.deptName || "暂无信息" }}
          </p>
          <p class="fontz fonts14 login_userinfo_p"><span>我的角色</span>：{{ state.my_Info.user.roles[0].roleName || "暂无信息"
            }}
          </p>
          <p class="fontz fonts14 login_userinfo_p"><span>账&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号</span>：{{
    state.my_Info.user.userName || "暂无信息" }}</p>
          <div class="flex jcsb">
            <div class="flex aic jcc login_change fonts16" @click="openEdit">修改密码</div>
            <div class="flex aic jcc login_changes fonts16" @click="loginOut">退出登录</div>
          </div>
        </div>
      </ElDropdownMenu>
    </template>
  </ElDropdown>
  <el-dialog v-model="dialogVisibleEdit" title="修改密码" width="440" :before-close="handleClose">
    <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
      status-icon>
      <el-form-item label="旧密码" prop="old_password">
        <el-input v-model="state.ruleForm.old_password" placeholder="请输入旧密码" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="state.ruleForm.password" placeholder="请输入新密码" type="password" />
      </el-form-item>
      <el-form-item label="确认密码" prop="again_password">
        <el-input v-model="state.ruleForm.again_password" placeholder="请确认密码" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm(ruleFormRef)" v-loading="loading">
          确定
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
  <LockDialog v-if="dialogVisible" v-model="dialogVisible" />
  <teleport to="body">
    <transition name="fade-bottom" mode="out-in">
      <LockPage v-if="getIsLock" />
    </transition>
  </teleport>
</template>

<style scoped lang="less">
.login_userinfo {
  padding: 20px;
  width: 280px;
  // height: 268px;
  background: #FFFFFF;
  box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.102);
  border-radius: 8px 8px 8px 8px;
  opacity: 1;

  p {
    color: #232327;
    display: flex;
  }

  .gray {
    color: #848797;
  }

  .login_userinfo_p {
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #EDF0F6;

    span {
      display: flex;
      width: 48px;
      text-align: justify;
    }
  }

  .login_userinfo_p1 {}

  .login_userinfo_ul {
    padding: 0;
    overflow-y: auto;
    height: 260px;

    &::-webkit-scrollbar {
      // 滚动条样式
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 5px;
      background: #D5D7DA;
    }

    li {
      padding: 12px 12px;
      background: #EFF3F7;
      border-radius: 8px 8px 8px 8px;
      margin-bottom: 10px;

      img {
        width: 34px;
        height: 34px;
        margin-top: 2px;
        margin-right: 6px;
      }
    }
  }
}

.login_change {
  width: 116px;
  height: 40px;
  border-radius: 8px 8px 8px 8px;
  opacity: 1;
  border: 1px solid #979797;
  color: #3D3D3D;
}

.login_changes {

  width: 116px;
  height: 40px;
  background: #2F6CBC;
  border-radius: 8px 8px 8px 8px;
  opacity: 1;
  color: #FFFFFF;
}

.fade-bottom-enter-active,
.fade-bottom-leave-active {
  transition:
    opacity 0.25s,
    transform 0.3s;
}

.fade-bottom-enter-from {
  opacity: 0;
  transform: translateY(-10%);
}

.fade-bottom-leave-to {
  opacity: 0;
  transform: translateY(10%);
}
</style>
